package com.lb.shopguide.ui.activity;

/**
 * Created by kang on 2017/8/4.
 */

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseActivity;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.manager.interf.WebviewInterface;
import com.lb.shopguide.ui.dialog.DialogShare;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.FileUtilsExt;
import com.lb.shopguide.util.lb.BizUtil;
import com.netease.nim.uikit.common.util.log.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;


/**
 * Created by kang on 2017/8/3.
 */

public class ActivityActivityDetail extends BaseActivity implements WebviewInterface {
    private String title;
    protected Context mContext;
    protected BridgeWebView mWebView;
    protected ProgressBar progressBar;
    protected NormalTitleBar ntb;

    private LbReceiver mLbReceiver;

    private String barcode;
    protected String webUrl;
    private CallBackFunction barcodeCallBackFunction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //取消状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        setContentView(R.layout.activity_webview);
        initData();
        initView();
        registerReceiver();

    }


    public void initData() {
        mLbReceiver = new LbReceiver();
        mContext = ActivityActivityDetail.this;

    }

    private void initBundle() {
        Bundle bundle = getIntent().getExtras();
        if (bundle.containsKey(AppConstant.WEB_URL)) {
            webUrl = bundle.getString(AppConstant.WEB_URL);
        }
        if (bundle.containsKey(AppConstant.WEB_TITLE)) {
            title = bundle.getString(AppConstant.WEB_TITLE);

        }
        if (TextUtils.isEmpty(title)) {
            ntb.setVisibility(View.GONE);
        } else {
            ntb.setVisibility(View.VISIBLE);
            ntb.setTitleText(title);
        }
        LogUtils.d("ActivityActivityDetail====weburl" + webUrl + "====WEB_TITLE=====" + title);
    }

    public void initView() {
        ntb = findViewById(R.id.ntb);
        mWebView = findViewById(R.id.webview);
        progressBar = findViewById(R.id.progress_bar);

        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        initBundle();

        // 进度条控制
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress >= 100) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                }
                super.onProgressChanged(view, newProgress);
            }

        });

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setLightTouchEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setTextSize(WebSettings.TextSize.NORMAL);
//        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setDefaultHandler(new DefaultHandler());
        mWebView.loadUrl(webUrl);

        LogUtils.i("WebView", "UA: " + mWebView.getSettings().getUserAgentString());
        share();
        getBarcode();
        call();
        savePic();
        charge();
        backToActivityList();

    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConstant.BROADCAST_WAP_QRPAY);
        registerReceiver(mLbReceiver, intentFilter);
    }

    private void unRegisterReceiver() {
        if (mLbReceiver != null) {
            this.unregisterReceiver(mLbReceiver);
        }
    }

    @Override
    public void share() {
        mWebView.registerHandler("share", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                //{"imgUrl":"","content":"告诉你一个秘密，这种好事，去哪里都找不到，就是这家我常去的服装店，国庆中秋各种送礼了！好朋友才分享给你！机会貌似不多了！快来吧！","title":"告诉你一个秘密","linkUrl":""}
                try {
                    final JSONObject jsonObject = new JSONObject(data);
                    final String url = jsonObject.getString("linkUrl");
//                    final String imgUrl = jsonObject.getString("imgUrl");
                    final DialogShare dialogShare = BizUtil.showShareDialog(getSupportFragmentManager(), url);
                    if (dialogShare != null) {
                        dialogShare.setOnPlatformClickListener(new DialogShare.OnSharePlatformClick() {
                            @Override
                            public void onPlatformClick(int id) {
                                switch (id) {
                                    case R.id.ly_share_weichat_circle:
                                        dialogShare.dismiss();
                                        try {
                                            BizUtil.share(mContext, jsonObject.getString("title"), jsonObject.getString("content"), jsonObject.getString("linkUrl"),
                                                    jsonObject.getString("imgUrl"), AppConstant.SHARE_WECHAT_CIRCLE);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        break;
                                    case R.id.ly_share_weichat:
                                        dialogShare.dismiss();
                                        try {
                                            BizUtil.share(mContext, jsonObject.getString("title"), jsonObject.getString("content"), jsonObject.getString("linkUrl"),
                                                    jsonObject.getString("imgUrl"), AppConstant.SHARE_WECHAT);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        break;
                                }
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void getBarcode() {
        mWebView.registerHandler("getBarcode", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                barcodeCallBackFunction = function;
                Intent intent = new Intent(mContext, ScanSmallActivity.class);
                intent.putExtra(AppConstant.SCAN_MODE, AppConstant.SCAN_RETURN_BARCODE);
                startActivityForResult(intent, AppConstant.REQUEST_CODE_GET_BAR_CODE);
            }
        });
    }

    @Override
    public void call() {
        mWebView.registerHandler("call", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                PhoneUtils.dial(data);
            }
        });
    }

    @Override
    public void savePic() {
        mWebView.registerHandler("savePic", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String name = "_android_" + BizUtil.getRandomName(3) + AppConstant.PNG;
                FileUtilsExt.saveImageToGallery(mContext, name, BizUtil.stringToBitmap(data));
                ToastUtils.showShort("保存图片成功");
            }
        });
    }

    @Override
    public void charge() {
        mWebView.registerHandler("charge", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                // TODO: 2018/4/23 充值
            }
        });
    }

    @Override
    public void backToActivityList() {
        mWebView.registerHandler("backToActivityList", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                finish();
            }
        });
    }

    @Override
    public void goToMyActivity() {

    }

    @Override
    public void backToHome() {

    }

    @Override
    public void backToPrePage() {

    }

    public class LbReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(AppConstant.BROADCAST_WAP_QRPAY)) {
                Bundle bundle = intent.getExtras();
                String orderNum = null;
                try {
                    JSONObject jsonObject = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    orderNum = jsonObject.getString("orderNum");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mWebView.callHandler("paySuccess", orderNum, new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {

                    }
                });
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == AppConstant.REQUEST_CODE_GET_BAR_CODE) {
                barcode = data.getStringExtra(AppConstant.BARCODE);
                barcodeCallBackFunction.onCallBack(barcode);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterReceiver();
    }

}

